﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Mammoth.Entities;
using Mammoth.Repositories;
using Mammoth.Services;

namespace Mammoth.ViewModels
{
    public class AddBuddyViewModel : WPFViewModelBase
    {
        IGTalkService GTalkService;
        IRepositoryFactory RepoFactory;
        IGTalkConfiguration Configuration;

        public IList<AccountEntity> AccountList { get; set; }
        public AccountEntity SelectedAccount { get; set; }
        public string BuddyEmail { get; set; }

        public AddBuddyViewModel(IInputElement dispatcher, IGTalkService gtalkService, IRepositoryFactory repoFactory, IGTalkConfiguration config)
            : base(dispatcher)
        {
            GTalkService = gtalkService;
            RepoFactory = repoFactory;
            Configuration = config;
            PopulateAccountListAsync();
        }

        private void PopulateAccountListAsync()
        {
            Task.Factory.StartNew(PopulateAccountList);
        }

        private void PopulateAccountList()
        {
            AccountList = new ObservableCollection<AccountEntity>();
            for (int i = 0; i < Configuration.Accounts.Count; i++)
            {
                var acc = (AccountEntity)Configuration.Accounts[i];
                AccountList.Add(acc);
                if (i == 0)
                    SelectedAccount = acc;
            }
        }

        public void SubscribeHandler()
        {
            Subscribe(BuddyEmail, SelectedAccount.Email);
        }
    
        public void Subscribe(string serviceEmail, string buddyEmail)
        {
            GTalkService.Subscribe(serviceEmail, buddyEmail);
        }
    }
}
